package cn.flyme.shop.controller;

import cn.flyme.shop.service.VcodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;


@Controller
@RequestMapping("/code")
public class CodeController {

    @Autowired
    VcodeService vcodeService = null;


    /**
     * 获取验证码
     */
    @RequestMapping(path = "/pic",method = RequestMethod.GET)
    public void vcodeGet(@RequestParam(value = "ts",required = false) String ts,
                         HttpSession session, HttpServletResponse response){
        response.setContentType("image/jpeg");
        //将得到的随机字符串放到session中
        String randomString  = vcodeService.getRandomString();
        session.setAttribute("vcode",randomString);
        //得到图片
        BufferedImage bi = vcodeService.getImage(randomString);

        try {
            ImageIO.write(bi, "JPEG", response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
